<template>
  <!-- 可以做成选择数据后再显示操作按钮的，但懒的改了，后面再看 -->
  <div>
    <!-- 页头 -->
    <x-header style="background-color:#10aeff;">权限管理</x-header>
    <!-- /页头 -->

    <!-- 类型选择按钮 -->
    <divider>权限类型</divider>
    <div style="margin: 0 15px;">
      <x-button @click.native="selectPicker = true" type="primary"> {{ selectType[0] }}</x-button>
    </div>
    <!-- /类型选择按钮 -->

    <!-- 操作按钮组 -->
    <divider>操作</divider>
    <div style="margin: 0 15px;">
      <x-button mini plain @click.native="addshow = true">新增</x-button>
      <x-button mini type="primary" @click.native="updatePicker = true">修改</x-button>
      <x-button mini type="warn" @click.native="delPicker = true">删除</x-button>
    </div>
    <!-- /操作按钮组 -->

    <!-- 修改弹窗 -->
    <div v-transfer-dom>
      <popup v-model="updatePicker" position="bottom" max-height="50%">
        <checklist ref="demoObject" title="请选择要修改的权限" :max="1" :options="keydata" v-model="updateListValue"></checklist>
        <div style="padding: 15px;">
          <x-button @click.native="update" mini plain type="primary"> 确 定</x-button>
          <x-button @click.native="updatePicker = false" mini plain type="warn" style="align:right"> 取 消 </x-button>
        </div>
      </popup>
    </div>
    <!-- /修改弹窗 -->

    <!-- 删除弹窗 -->
    <div v-transfer-dom>
      <popup v-model="delPicker" position="bottom" max-height="50%">
        <checklist ref="demoObject" title="请选择要修改的权限" :max="1" :options="keydata" v-model="updateListValue"></checklist>
        <div style="padding: 15px;">
          <x-button @click.native="del" mini plain type="primary"> 确 定</x-button>
          <x-button @click.native="delPicker = false" mini plain type="warn" style="align:right"> 取 消 </x-button>
        </div>
      </popup>
    </div>
    <!-- /删除弹窗 -->

    <!-- 提示弹窗 -->
    <div v-transfer-dom>
      <alert v-model="alertshow" title="提示"> 请选择权限后操作</alert>
    </div>
    <!-- 提示弹窗 -->

    <!-- 修改权限真窗体 -->
    <div v-transfer-dom>
      <confirm v-model="updateshow" title="修改权限" @on-confirm="onConfirmUpdate">
        <group>
          <x-input align="left" title="ID" disabled v-model="updateObj.id"></x-input>
          <!-- <datetime title="时&emsp;&emsp;&nbsp;间" value-text-align="left"></datetime> -->
          <x-input align="left" title="名称" v-model="updateObj.Jurisdiction_name"></x-input>
          <x-input align="left" title="路径" v-model="updateObj.Jurisdiction_path "></x-input>
          <selector align="left" title="类型" :options="['router', 'button']" v-model="updateObj.Jurisdiction_type"></selector>
          <x-input align="left" title="父级ID" v-model="updateObj.parent_id"></x-input>
          <!-- <x-textarea title="详细信息" placeholder="请填写详细信息" :show-counter="false" :rows="3"></x-textarea> -->
        </group>
      </confirm>
    </div>
    <!-- /修改权限真窗体 -->

    <!-- 新增权限窗体 -->
    <div v-transfer-dom>
      <confirm v-model="addshow" title="新增权限" @on-confirm="onConfirmAdd">
        <group>
          <!-- <datetime title="时&emsp;&emsp;&nbsp;间" value-text-align="left"></datetime> -->
          <x-input align="left" title="名称" v-model="addObj.Jurisdiction_name"></x-input>
          <x-input align="left" title="路径" v-model="addObj.Jurisdiction_path"></x-input>
          <selector align="left" title="类型" :options="['router', 'button']" v-model="addObj.Jurisdiction_type"></selector>
          <x-input align="left" title="父级ID" v-model="addObj.parent_id"></x-input>
          <!-- <x-textarea title="详细信息" placeholder="请填写详细信息" :show-counter="false" :rows="3"></x-textarea> -->
        </group>
      </confirm>
    </div>
    <!-- /新增权限窗体 -->

    <!-- 成功提示 -->
    <toast v-model="handleSuccess" :time="500">操作成功</toast>
    <!-- /成功提示 -->

    <!-- 类型选择 -->
    <group>
      <popup-picker :show.sync="selectPicker" :show-cell="false" :data="[['PC端', '移动端']]" v-model="selectType"></popup-picker>
    </group>
    <!-- /类型选择 -->

    <!-- 一行字 -->
    <load-more tip="权限详情" :show-loading="false" background-color="#fbf9fe"></load-more>
    <!-- /一行字 -->

    <!-- table -->
    <x-table :cell-bordered="true" :content-bordered="true" style="background-color:#fff;padding:0 10px">
      <thead>
        <tr style="background-color: #F7F7F7">
          <th>ID</th>
          <th>名称</th>
          <th>路径</th>
          <th>类型</th>
          <th>父级ID</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td style="text-align: left;">{{ item.id}}</td>
          <td style="text-align: left;">{{ item.Jurisdiction_name }}</td>
          <td style="text-align: left;">{{ item.Jurisdiction_path | notNull}}</td>
          <td style="text-align: left;">{{ item.Jurisdiction_type}}</td>
          <td style="text-align: left;">{{ item.parent_id}}</td>
        </tr>
      </tbody>
    </x-table>
    <!-- /table -->

  </div>
</template>

<script>
import {
  Cell,
  CellBox,
  XButton,
  Group,
  LoadMore,
  XHeader,
  PopupPicker,
  Divider,
  XTable,
  TransferDom,
  Popup,
  Checklist,
  Alert,
  XInput,
  Confirm,
  Selector,
  XNumber,
  XTextarea,
  Datetime,
  Toast
} from "vux";
import Icon from "vue-awesome/components/Icon";
import "vue-awesome/icons/folder-open";
import axios from "axios";
export default {
  directives: {
    TransferDom
  },
  components: {
    Popup,
    Cell,
    CellBox,
    XButton,
    Group,
    LoadMore,
    XHeader,
    Icon,
    PopupPicker,
    Divider,
    XTable,
    Checklist,
    Alert,
    XInput,
    Confirm,
    Selector,
    XNumber,
    XTextarea,
    Datetime,
    Toast
  },
  data() {
    return {
      // 类型选择的存储
      selectType: ["PC端"],
      // 类型选择的弹窗是否显示
      selectPicker: false,
      // 修改数据，删除数据在选中后会push到这里（名字懒的改了）
      updateListValue: [],
      // 修改选择是否显示
      updatePicker: false,
      // 原始数据
      data: [],
      // 增加key后的数据
      keydata: [],
      // 提示选择数据后操作
      alertshow: false,
      // 修改选择真窗口是否显示
      updateshow: false,
      // 修改用的数据对象
      updateObj: {},
      // 操作是否成功
      handleSuccess: false,
      // 删除选择是否显示
      delPicker: false,
      // 增加窗口是否显示
      addshow: false,
      // 增加用的对象
      addObj: {
        Jurisdiction_name: "",
        Jurisdiction_path: "",
        Jurisdiction_type: "",
        parent_id: null,
        type: null
      }
    };
  },
  filters: {
    //过滤器，美化table中的null
    notNull: function(value) {
      return value === "null" ? "" : value;
    }
  },
  watch: {
    // 根据权限的类型不同获取不通的数据
    selectType: function(newvalue, oldvalue) {
      this.getInfo();
    }
  },
  created() {
    // 获取初始数据
    this.getInfo();
  },
  methods: {
    // 确认增加，发送请求后清空变量并重新获取数据
    async onConfirmAdd() {
      await this.addInfo();
      this.addObj.Jurisdiction_name = "";
      this.addObj.Jurisdiction_path = "";
      this.addObj.Jurisdiction_type = "";
      this.addObj.parent_id = null;
      this.addObj.type = null;
      this.getInfo();
    },
    // 确认修改，清空已选择数组，发送修改请求，重新获取数据
    async onConfirmUpdate() {
      this.updateListValue = [];
      await this.updateInfo();
      this.getInfo();
    },
    // 删除，如果未选择数据则弹出提示，否则获取id，清空已选择数组，发送删除请求，重新获取数据
    async del() {
      if (!this.updateListValue.length) {
        this.alertshow = true;
      } else {
        let index = this.updateListValue[0] - 1;
        this.updateObj.id = this.data[index].id;
        this.updateListValue = [];
        await this.delInfo();
        this.getInfo();
        this.delPicker = false;
      }
    },
    // 修改数据，如未选择数据则弹出提示，否则获取并保存选择的数据，然后弹出真修改数据窗口
    update() {
      if (!this.updateListValue.length) {
        this.alertshow = true;
      } else {
        let index = this.updateListValue[0] - 1;
        this.updatePicker = false;
        this.updateObj.id = this.data[index].id;
        this.updateObj.Jurisdiction_name = this.data[index].Jurisdiction_name;
        this.updateObj.Jurisdiction_path = this.data[index].Jurisdiction_path;
        this.updateObj.Jurisdiction_type = this.data[index].Jurisdiction_type;
        this.updateObj.parent_id = this.data[index].parent_id;
        this.updateshow = true;
      }
    },
    // 获取数据列表请求，根据选择的类型，返回不同的数据
    async getInfo() {
      let searchType = 0;
      if (this.selectType[0] == "移动端") searchType = 1;
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `{ jurisdictionListByType(type:${searchType}){id,parent_id,Jurisdiction_name,Jurisdiction_path,Jurisdiction_type}}`
        });
        this.data = [];
        this.data = info.data.data.jurisdictionListByType;
        // 因为组件需要key，而原始数据没有，调用此方法增加
        this.getKeydata();
      } catch (error) {
        console.error(error);
      }
    },
    // 删除数据请求
    async delInfo() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{ jurisdictionDel(id:${this.updateObj.id})}`
        });
        // 成功则弹成功
        if (info.data) this.handleSuccess = true;
      } catch (error) {
        console.error(error);
      }
    },
    // 修改数据请求
    async updateInfo() {
      let searchType = 0;
      if (this.selectType[0] == "移动端") searchType = 1;
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{ jurisdictionUpdate(id:${
            this.updateObj.id
          },parent_id:${this.updateObj.parent_id},type:${searchType}
          ,
          Jurisdiction_name:"${
            this.updateObj.Jurisdiction_name
          }",Jurisdiction_path:"${
            this.updateObj.Jurisdiction_path
          }",Jurisdiction_type:"${this.updateObj.Jurisdiction_type}")}`
        });
        // 成功则弹成功窗
        if (info.data) this.handleSuccess = true;
      } catch (error) {
        console.error(error);
      }
    },
    // 新增数据请求，根据当前的类型自动填入type
    async addInfo() {
      let searchType = 0;
      if (this.selectType[0] == "移动端") searchType = 1;
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{ jurisdictionAdd(parent_id:${
            this.addObj.parent_id
          },type:${searchType}
          ,
          Jurisdiction_name:"${
            this.addObj.Jurisdiction_name
          }",Jurisdiction_path:"${
            this.addObj.Jurisdiction_path
          }",Jurisdiction_type:"${this.addObj.Jurisdiction_type}"){id}}`
        });
        // 成功则弹成功窗
        if (info.data) this.handleSuccess = true;
      } catch (error) {
        console.error(error);
      }
    },
    // 给原始数据增加key，因为0在组件中无法选中，所以+1，在使用时请-1，否则会越界
    getKeydata() {
      this.keydata = [];
      for (let index = 0; index < this.data.length; index++) {
        let temp = {
          key: index + 1,
          value: `名称:${this.data[index].Jurisdiction_name} | 路径:${
            this.data[index].Jurisdiction_path
          } | 类型:${this.data[index].Jurisdiction_type} | 父级ID:${
            this.data[index].parent_id
          }`
        };
        this.keydata.push(temp);
      }
    }
  }
};
</script>


